package com.wwwc.admin.web.servlet;

import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletRequestWrapper;

public class adminGenerateImageList extends HttpServlet {
    private Vector vd = null;
    private StringBuffer sbf = null;

    public void doGet(HttpServletRequest request,  HttpServletResponse response)
	throws IOException, ServletException
    {
	doPost(request,response);
    }

    public void doPost(HttpServletRequest request, 
		       HttpServletResponse response)
	throws IOException, ServletException
    {
        response.setContentType("text/html");

	HttpSession session = request.getSession(true);
        PrintWriter out     = response.getWriter();
	String user_ip      = request.getRemoteAddr();

	String action    = request.getParameter("action");
	String options   = request.getParameter("options");

	if(action == null) {
	    out.println("<HTML><HEAD><TITLE></TITLE>");
	    out.println("</HEAD><BODY>");
	    out.println("<FORM method=post action adminGenerateImageList>");
	    out.println("<TABLE border=1 width=100%>");
	    out.println("<TR><TD align=center colspan=2>This is a utility for generate a directory index</TD></TR>");
	    out.println("<TR><TD align=center>Title</TD>");
	    out.println("<TD><input type=text name=title size=90></TD></TR>");
	    out.println("<TR><TD align=center>Directory</TD>");
	    out.println("<TD><input type=text name=dir size=90></TD></TR>");
	    out.println("<TR><TD></TD><TD><input type=submit name=B value=Submit>");
	    out.println("<input type=reset name=R value=Reset></TD></TR>");
	    out.println("<input type=hidden name=action value=gdir>");
	    out.println("</TABLE>");
	    out.println("</FORM>");
	    out.println("</BODY></HTML>");
	    return;
	}
	else if (action.equals("gdir")) {
	    String title = request.getParameter("title");
	    String dir   = request.getParameter("dir");
	    if(dir==null || dir.length()<1 || !(new File(dir)).isDirectory()) {
		out.println("Please enter a diretory.");
		return;
	    }
	   
	    File df = new File (dir);
	    vd = new Vector();
	    loadSubdir(df);
	    File sd = null;

	    for(int i=0; i<vd.size();i++) {
		sd = (File)vd.elementAt(i);
		loadSubdir(sd);
	    }
	    out.println((vd.toString()).replaceAll(",","<BR>"));

	    String slist[] = df.list();
	    sbf = new StringBuffer();
	    String cname = null;
	    for(int i=0; i<slist.length; i++) {
		sd = new File(dir,slist[i]);
		if(sd.isDirectory()) {
		    sbf.append("<BR>"+sd.getName()+"<BR>");
		    sbf.append("<A>"+getChildName(sd.getPath(),vd)+"</A>");
		}
	    }
	    out.println(sbf);
	    //
	    //printList(dir, vd);
	    //gFrameIndexFile(dir, vd);
	}
    }

    private boolean containsFile(String dir) {
	File sf[] = (new File(dir)).listFiles();
	for(int i=0; i<sf.length; i++) {
	    if(sf[i].isFile()) {
		return true;
	    }
	}
	return false;
    }

    private boolean containsDir(String dir) {
	
	File sf[] = (new File(dir)).listFiles();
	for(int i=0; i<sf.length; i++) {
	    if(sf[i].isDirectory()) {
		return true;
	    }
	}
	return false;
    }

    private String getChildName(String pname, Vector v) {
	Enumeration enum = v.elements();
	String temp  = null;
	String sname = null;
	String next  = null;
	while(enum.hasMoreElements()) {
	    temp = ""+enum.nextElement();
	    if(temp.startsWith(pname) && !temp.equals(pname)) {
		sname = temp.substring(pname.length()+1);
		if(sname.indexOf("\\")==-1) {
		    sbf.append("<BR>&nbsp;"+sname);
		}
		else {
		    next = sname;
		}
	    }
	}

	return next;
    }

    private void loadSubdir(File f) {
	File index_f = null;
	if(f.isDirectory()) {
	    index_f = new File(f.getPath(),"index.html");
	    int n=0;
	    while(index_f.exists()) {
		n++;
		index_f.delete();
		if(n>5) {
		    break;
		}
	    }

	    File sf[] = f.listFiles();
	    for(int i=0; i<sf.length; i++) {
		if(sf[i].isDirectory() && (sf[i].list()).length>0) {
		    if(!vd.contains(sf[i])) {
			vd.add(sf[i]);
		    }
		}
	    }
	}
    }

    private void gIndexFile(String title, String dir, String[] file_list) {

	File f = new File(dir,"index.html");
	while(f.exists()) {
	    f.delete();
	    f = new File(dir,"index.html");
	}

	try {
	    RandomAccessFile outputFile = new RandomAccessFile(f, "rw" );
	    outputFile.writeBytes("<HTML><HEAD><TITLE>image index</TITLE>");
	    outputFile.writeBytes("<SCRIPT>");
	    outputFile.writeBytes("var db = new Array("+file_list.length+");");
	    for(int i=0; i<file_list.length;i++) {
		outputFile.writeBytes("db["+i+"]=\""+file_list[i]+"\";");
	    }

	    outputFile.writeBytes("function changeImage(m) {");
	    outputFile.writeBytes("    for(i=0;i<db.length;i++){");
	    outputFile.writeBytes("       if(document.pic.src.indexOf(\"/\"+db[i]) != -1){");
	    outputFile.writeBytes("          if(m==1) {");
	    outputFile.writeBytes("             if(i==(db.length-1)) {");
	    outputFile.writeBytes("                 i=-1;");
	    outputFile.writeBytes("             }");
	    outputFile.writeBytes("             document.pic.src=db[(i+1)];");
	    outputFile.writeBytes("             document.forms.f.counter.value=(i+1)+\"/\"+db.length;");
	    outputFile.writeBytes("          }");
	    outputFile.writeBytes("          if(m==-1) {");
	    outputFile.writeBytes("              if(i==0) {");
	    outputFile.writeBytes("                  i = db.length;");
	    outputFile.writeBytes("              }");
	    outputFile.writeBytes("              document.pic.src=db[(i-1)];");
	    outputFile.writeBytes("              document.forms.f.counter.value=(i-1)+\"/\"+db.length;");
	    outputFile.writeBytes("          }");
	    outputFile.writeBytes("          break;");
	    outputFile.writeBytes("       }");
	    outputFile.writeBytes("    }");
	    outputFile.writeBytes("}");

	    outputFile.writeBytes("function resizeImage() {");
	    outputFile.writeBytes("   var w = document.pic.width;");
	    outputFile.writeBytes("   var h = document.pic.height;");
	    outputFile.writeBytes("   while (w>700) {");
	    outputFile.writeBytes("     w = w*0.9;");
	    outputFile.writeBytes("   }");
	    outputFile.writeBytes("  document.pic.width  = w;");
	    outputFile.writeBytes("}");
	    outputFile.writeBytes("</SCRIPT>");
	    outputFile.writeBytes("</HEAD>");
	    outputFile.writeBytes("<BODY><CENTER>");
	    /*
	    outputFile.writeBytes("<TABLE border=0 width=800 style='font-size:10pt'>");
	    outputFile.writeBytes("<TR><TD align=center>"+title+"</TD></TR>");
	    outputFile.writeBytes("</TABLE>");
	    */
	    //outputFile.writeBytes("<TR><TD align=center>");
	    outputFile.writeBytes("<TABLE border=1 width=800 height=500>");
	    outputFile.writeBytes("<FORM name=f>");
	    outputFile.writeBytes("<TR><TD align=center>");
	    outputFile.writeBytes("<input type=button name=B1 value=Back style='font-size: 8pt' ");
	    outputFile.writeBytes(" onclick=javascript:changeImage(-1);>");
	    outputFile.writeBytes("<input type=button name=counter value=0/"+file_list.length);
	    outputFile.writeBytes(" style='font-size: 8pt'>");
	    outputFile.writeBytes("<input type=button name=B2 value=Next style='font-size: 8pt' ");
	    outputFile.writeBytes(" onclick=javascript:changeImage(1);>");
	    outputFile.writeBytes("</TD></TR>");
	    outputFile.writeBytes("</FORM>");
	    outputFile.writeBytes("<TR><TD align=center>");
	    outputFile.writeBytes("<img name=pic src="+file_list[0]+" border=0");
	    outputFile.writeBytes(" onLoad=javascript:resizeImage();>");
	    outputFile.writeBytes("</TD></TR>");
	    
	    outputFile.writeBytes("</TABLE></CENTER></BODY></HTML>");
	    outputFile.close();
	}
	catch ( IOException e ) {

	}
    }

    private void gFrameIndexFile(String dir, Vector v) {

	File f = new File(dir,"index_left.html");
	while(f.exists()) {
	    f.delete();
	    f = new File(dir,"index_left.html");
	}
	
	try {
	    RandomAccessFile outputFile = new RandomAccessFile(f, "rw" );
	    outputFile.writeBytes("<HTML><HEAD><TITLE>image index bar</TITLE>");
	    outputFile.writeBytes("</HEAD>");
	    outputFile.writeBytes("<BODY>");
	    outputFile.writeBytes("<TABLE border=0 width=150 style='font-size:8pt'>");

	    String user_home = "C:\\myServers\\ApacheGroup\\Apache2\\htdocs\\users\\eileen";
	    Enumeration enum = v.elements();
	    Enumeration enums = null;
	    String temp = null;
	    String temps = null;
	    while(enum.hasMoreElements()) {
		temp = ""+enum.nextElement();
		//System.out.println(user_home);
		//System.out.println(temp);
		//temp  = temp.substring(user_home.length()+1);
		if(containsFile(temp)) {
		    System.out.println(temp+" containsFile");
		    outputFile.writeBytes("<TR><TD align=left>");
		    outputFile.writeBytes("<A href=./"+temp.substring(user_home.length()+1)+"/index.html target=mainFrame>");
		    outputFile.writeBytes((temp.substring(user_home.length()+1)).toUpperCase());
		    outputFile.writeBytes("</A></TD></TR>");
		}

		if(containsDir(temp)) {
		    System.out.println(temp+" containsDir");
		    outputFile.writeBytes("<TR><TD align=left>");
		    outputFile.writeBytes((temp.substring(user_home.length()+1)).toUpperCase()+"</TD></TR>");
		    outputFile.writeBytes("<TR><TD align=left>");
		    outputFile.writeBytes("<A href=./index.html target=mainFrame></A></TD></TR>");
		}
	    }
	    outputFile.writeBytes("</TABLE></BODY></HTML>");
	    outputFile.close();
	}
	catch ( IOException e ) {

	}
	/*
	f = new File(dir,"index.html");
	while(f.exists()) {
	    f.delete();
	    f = new File(dir,"index.html");
	}

	try {
	    RandomAccessFile outputFile = new RandomAccessFile(f, "rw" );
	    outputFile.writeBytes("<html><head><title>image index</title></head>");
	    outputFile.writeBytes("<frameset cols=\"140,*\" framespacing=\"0\" border=\"0\" frameborder=\"0\">");
	    outputFile.writeBytes("<frame name=\"leftFrame\" scrolling=\"auto\" src=\"./index_left.html\">");
	    outputFile.writeBytes("<frame name=\"mainFrame\" scrolling=\"auto\" src=\"./"+dir_list[0]+"/index.html\">");  
	    outputFile.writeBytes("<noframes>");
	    outputFile.writeBytes("<body>");
	    outputFile.writeBytes("<p>This page uses frames, but your browser doesn't support them.</p>");
	    outputFile.writeBytes("</body>");
	    outputFile.writeBytes("</noframes>");
	    outputFile.writeBytes("</frameset>");
	    outputFile.writeBytes("</html>");
	    outputFile.close();
	}
	catch ( IOException e ) {

	}
	*/
	}

   
    /*
	
       	String dir_id[] = null;
	StringBuffer sb = new StringBuffer ();
	Vector pro_v = new Vector();
	File f ;

	f = new File (inProfile);
	if (!f.isFile()) {
	    sb.append("<BR>Profile not found:");
	}
	else {
	    ProfileLoader loader = new ProfileLoader();
	    loader.setFileName(inProfile);
	    loader.loadProfile();
	    pro_v = loader.getVector();
	}

	f = new File (outHtmlfile);
	if (f.isFile()) {
	    f.delete();
	    sb.append("<BR>Delete:"+outHtmlfile);
	}
	else {
	    f = new File (outHtmlfile.substring(0, outHtmlfile.lastIndexOf("\\")));
	    if (!f.isDirectory()) {
		f.mkdirs();
	    }
	}

	String current_dir = inProfile.substring((inProfile.indexOf("htdocs\\")+6),inProfile.lastIndexOf("\\"));

	sb.append("<BR>current_dir="+current_dir);

	try {
	    RandomAccessFile outputFile = new RandomAccessFile( (outHtmlfile), "rw" );
	    outputFile.writeBytes("<HTML><HEAD><TITLE>Direcotry:["+current_dir+"] index</TITLE>");

	   
	    outputFile.writeBytes("</HEAD>\n");
	    outputFile.writeBytes("<BODY>\n");
	    outputFile.writeBytes("<TABLE border='0' width='300' height='100'>\n");
	    outputFile.writeBytes("<TR><TD><A href=/3wcg.html><IMG height ='100' width='100' border=0 ");
	    outputFile.writeBytes("src=/_system/images/3wc.JPG></A>\n");
	    outputFile.writeBytes("</TD></TR>\n</TABLE>\n<TABLE>\n");

	    outputFile.writeBytes("<TR><TD><a href=/index/servlet/SideBarEditServlet target=mainFrame>\n");
	    outputFile.writeBytes("<img border=0 src=/_system/images/edit.gif></a></TD></TR>");

	    Vector dir_v = new Vector();

	    if (current_dir.indexOf("\\") != -1) {

		StringTokenizer tokens = new StringTokenizer(current_dir,"\\");
		String temp = null;
		outputFile.writeBytes("<tr><td><A href=/_system/html/index_left.html>\n");
		outputFile.writeBytes(serverName.toUpperCase()+"</A></TD></TR>\n");
		
		while (tokens.hasMoreTokens()) {
		    temp = (String)tokens.nextToken();
		    dir_v.add(temp);
		}
	    }
		
	    for (int j=0; j<dir_v.size();j++) {

		outputFile.writeBytes("<tr><td><IMG src=/_system/images/L"+(j+1)+".gif>");
		
		if (j==(dir_v.size()-1)) {
		    outputFile.writeBytes(((String)dir_v.elementAt(j)).toUpperCase()+"</TD></TR>\n");
		}
		else {
		    outputFile.writeBytes("<A href=/"+dir_v.elementAt(j)+">\n");
		    outputFile.writeBytes(((String)dir_v.elementAt(j)).toUpperCase()+"</A></TD></TR>\n");
		}
	    }

	    outputFile.writeBytes("<TR><TD>\n");

	    if (addJsfile.equals("no")) {
		String    url_name   = null;
		String    url_adds   = null;

		try {
		    Enumeration enum = pro_v.elements();  
		    while (enum.hasMoreElements()) {
			url_name = (String)enum.nextElement();
			url_adds = (String)enum.nextElement();
			outputFile.writeBytes("<A href ="+url_adds+">"+url_name.toUpperCase()+"</A><BR>\n");
		    }
		}
		catch ( IOException io ) {
		}
	    }

	    if (addJsfile.equals("yes")) {
		outputFile.writeBytes("<SCRIPT SRC='/_system/javaScript/setCookie.js'></SCRIPT>");
		outputFile.writeBytes("<SCRIPT SRC='/_system/javaScript/sideBarStateHead.js'></SCRIPT>");
		outputFile.writeBytes("<SCRIPT SRC='./_system/javaScript/sideBarStateBody.js'></SCRIPT>");
		outputFile.writeBytes("<SCRIPT SRC='/_system/javaScript/sideBarStateEnd.js'></SCRIPT>");
		outputFile.writeBytes("<SCRIPT SRC='/_system/javaScript/sideBarDisplay.js'></SCRIPT>");
	    }
	    
	    outputFile.writeBytes("</TD></TR></TABLE></BODY></HTML>");
	    outputFile.close();
	    sb.append("<BR>File: "+outHtmlfile+" has been generated");
	}
	catch ( IOException e ) {
	}
	return(sb.toString());
    }

    private String[] getDirList(String dir)
    {
	File dirName = new File (dir);
	return(dirName.list());
    }
    */
}



